package com.ruoyi.neo.repository;

import com.ruoyi.neo.domain.Part;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface PartRepository extends Neo4jRepository<Part,String> {
    // 查询所有零件
    @Query("MATCH (p:Part) RETURN p")
    List<Part> findAllPartsInNeo4j();

    // 根据零件ID查询零件
    @Query("MATCH (p:Part) WHERE p.partNumber = $partNumber RETURN p")
    Part findPartByNumberInNeo4j(@Param("partNumber") String partNumber);

    // 根据分类ID查询零件
    @Query("MATCH (p:Part)-[:BELONG_TO]->(c:PartCategory) WHERE c.categoryId = $categoryId RETURN p")
    List<Part> findPartsByCategoryIdInNeo4j(@Param("categoryId") Long categoryId);


    // 添加零件
    @Query("CREATE (p:Part {partName: $partName, partNumber: $partNumber,categoryId: $categoryId, description: $description}) RETURN p.partNumber")
    String addPartInNeo4j(@Param("partName") String partName,@Param("partNumber")String partNumber, @Param("categoryId") Long categoryId, @Param("description") String description);

    // 更新零件
    @Query("MATCH (p:Part) WHERE p.partName = $oldName SET p.partName = $partName, p.categoryId = $categoryId, p.description = $description RETURN count(p)")
    int updatePartInNeo4j(@Param("oldName") String oldName,@Param("partName") String partName,@Param("partNumber")String partNumber, @Param("categoryId") Long categoryId, @Param("description") String description);

    // 按照nameList删除零件
    @Query("MATCH (p:Part) WHERE p.partName IN $nameList DETACH DELETE p RETURN count(p)")
    int deletePartsInNeo4j(@Param("nameList") String[] nameList);
    // 将零件关联到分类
    @Query("MATCH (p:Part), (c:PartCategory) WHERE p.partName = $partName AND c.categoryName = $categoryName CREATE (p)-[:BELONG_TO]->(c)")
    void linkPartToCategory(@Param("partName") String partName, @Param("categoryName") String categoryName);

    // 取消零件与分类的关联
    @Query("MATCH (p:Part)-[r:BELONG_TO]->(c:PartCategory) WHERE p.partId = $partId AND c.categoryId = $categoryId DELETE r")
    boolean unlinkPartFromCategory(@Param("partId") Long partId, @Param("categoryId") Long categoryId);
}
